import { useState, useEffect } from 'react'
import { Editor } from '@tiptap/react'

interface HistoryEntry {
  id: string;
  content: string;
  timestamp: Date;
  description: string;
}

export const useEditorHistory = (editor: Editor | null) => {
  const [history, setHistory] = useState<HistoryEntry[]>([])
  const [currentIndex, setCurrentIndex] = useState<number>(-1)
  
  // 添加新的历史记录
  const addToHistory = (content: string, description: string = '内容更新') => {
    if (!content.trim()) return
    
    // 创建新的历史记录条目
    const newEntry: HistoryEntry = {
      id: Date.now().toString(),
      content,
      timestamp: new Date(),
      description
    }
    
    // 如果当前不是最新状态，则删除当前之后的历史
    if (currentIndex >= 0 && currentIndex < history.length - 1) {
      setHistory(prevHistory => {
        const newHistory = prevHistory.slice(0, currentIndex + 1)
        newHistory.push(newEntry)
        return newHistory
      })
    } else {
      // 否则直接添加到历史末尾
      setHistory(prevHistory => [...prevHistory, newEntry])
    }
    
    // 更新当前索引指向最新记录
    setCurrentIndex(prevIndex => 
      prevIndex >= 0 && prevIndex < history.length - 1 
        ? prevIndex + 1 
        : history.length
    )
  }
  
  // 监听编辑器内容变化
  useEffect(() => {
    if (!editor) return
    
    const handleUpdate = ({ editor }: { editor: Editor }) => {
      const content = editor.getHTML()
      
      // 防止频繁更新历史记录，可以添加防抖逻辑
      // 这里简化处理，实际应用中应该添加防抖
      if (history.length === 0 || content !== history[history.length - 1].content) {
        addToHistory(content)
      }
    }
    
    editor.on('update', handleUpdate)
    
    return () => {
      editor.off('update', handleUpdate)
    }
  }, [editor, history])
  
  // 恢复到特定历史记录
  const restoreToIndex = (index: number) => {
    if (!editor || index < 0 || index >= history.length) return
    
    const entryToRestore = history[index]
    editor.commands.setContent(entryToRestore.content)
    setCurrentIndex(index)
  }
  
  // 撤销 - 回到上一个历史记录
  const undo = () => {
    if (currentIndex > 0) {
      restoreToIndex(currentIndex - 1)
    }
  }
  
  // 重做 - 前进到下一个历史记录
  const redo = () => {
    if (currentIndex < history.length - 1) {
      restoreToIndex(currentIndex + 1)
    }
  }
  
  // 获取历史记录摘要（用于UI显示）
  const getHistorySummary = () => {
    return history.map((entry, index) => ({
      id: entry.id,
      timestamp: entry.timestamp,
      description: entry.description,
      isCurrent: index === currentIndex
    }))
  }
  
  return {
    history: getHistorySummary(),
    currentIndex,
    undo,
    redo,
    restoreToIndex,
    addToHistory
  }
} 